package cz.zcu.fav.ratdroid.xml;

import org.simpleframework.xml.convert.Converter;
import org.simpleframework.xml.stream.InputNode;
import org.simpleframework.xml.stream.OutputNode;
import cz.zcu.fav.ratdroid.bean.Period;
import cz.zcu.fav.ratdroid.bean.PickAction;
import cz.zcu.fav.ratdroid.bean.ReturnAction;
import cz.zcu.fav.ratdroid.service.RestUtils;

public class PeriodConverter implements Converter<Period>
{
	private static String PERIOD = "period";
	private static String PERIOD_ID = "id";
	private static String PERIOD_FROM_DATE = "fromDate";
	private static String PERIOD_TO_DATE = "toDate";
	private static String PERIOD_PICK_ACTION = "pickAction";
	private static String PERIOD_RETURN_ACTION = "returnAction";
	private static String PERIOD_VALID = "valid";

	public Period read(InputNode node) throws Exception
	{
		Period period = new Period();
		InputNode child;
		while ((child = node.getNext()) != null)
		{
			fillPeriod(period, child);
		}
		return period;
	}

	private void fillPeriod(Period period, InputNode node) throws Exception
	{
		String value = node.getValue();
		if (node.getName().equals(PERIOD_ID))
		{
			period.setId(Integer.valueOf(value));
		} else if (node.getName().equals(PERIOD_FROM_DATE))
		{
			period.setFromDate(RestUtils.convertRestTimeToJodaTime(value));
		} else if (node.getName().equals(PERIOD_TO_DATE))
		{
			period.setToDate(RestUtils.convertRestTimeToJodaTime(value));
		} else if (node.getName().equals(PERIOD_PICK_ACTION))
		{
			period.setPickAction(PickAction.valueOf(value));
		} else if (node.getName().equals(PERIOD_RETURN_ACTION))
		{
			period.setReturnAction(ReturnAction.valueOf(value));
		} else if (node.getName().equals(PERIOD_VALID))
		{
			period.setValid(Boolean.valueOf(value));
		}
	}

	public void write(OutputNode node, Period value) throws Exception
	{
		OutputNode periodNode = node;
		periodNode.getParent().getAttributes().remove("class"); //not required
		if (value.getId() != null)
		{
			OutputNode idNode = periodNode.getChild(PERIOD_ID);
			idNode.setValue(value.getId() + "");
		}
		OutputNode fromDateNode = periodNode.getChild(PERIOD_FROM_DATE);
		fromDateNode.setValue(RestUtils.convertJodaTimeToRestTime(value
				.getFromDate()));
		OutputNode toDateNode = periodNode.getChild(PERIOD_TO_DATE);
		toDateNode.setValue(RestUtils.convertJodaTimeToRestTime(value
				.getToDate()));
		OutputNode pickActionNode = periodNode.getChild(PERIOD_PICK_ACTION);
		pickActionNode.setValue(value.getPickAction().name());
		OutputNode returnActionNode = periodNode.getChild(PERIOD_RETURN_ACTION);
		returnActionNode.setValue(value.getReturnAction().name());
		OutputNode validNode = periodNode.getChild(PERIOD_VALID);
		validNode.setValue(Boolean.toString(value.isValid()));
	}

}
